<template>
  <div style="padding: 30px;">
    <button v-show="false" id="ky-link" @click="getLinks()"></button>
    <editor id="tinymce" v-model="editContent" :init="editConfig"></editor>
    <!-- <div style="text-align:left;" v-html="content"></div> -->
    <div
          :class="isLink?'single-more-articles border-radius-5 single-more-articles--visible':'single-more-articles border-radius-5'">
          <div class="widget-header-2 position-relative mb-30">
            <h5 class="mt-5 mb-30">
              文章互连：为你推荐
            </h5>
            <button class="single-more-articles-close" @click="closeLink"><i
                class="elegant-icon icon_close"></i></button>
          </div>
          <div v-loading="isLinkSearch">
            <span v-if="linkRec.rec.length == 0">😔目前还没有发现相关的文章，博主们正在火速创作~</span>
          <div class="post-block-list post-module-1 post-module-5">
            <div class="noy" style="height:200px; width:290px; overflow:auto" infinite-scroll-distance='1' v-infinite-scroll="load">
                  <ul class="list-post">
              <li class="mb-30" v-for="(item,i) in linkRec.rec" :key="i">
                <div class="d-flex hover-up-2 transition-normal">
                  <div class="post-thumb post-thumb-80 d-flex mr-15 border-radius-5 img-hover-scale overflow-hidden">
                    <a a @click="$commons.toWindodBlog(item.id)" href="javascript:void(0)" class="color-white">
                      <img :src="item.background" alt="">
                    </a>
                  </div>
                  <div class="post-content media-body">
                    <el-tooltip content="添加至当前写作" style="float:left;" class="mt-10 mr-5" placement="top" effect="light">
                          <i class="el-icon-document-add" @click="setSelectionLink('#/blog/'+item.id,'《'+item.title+'》')"></i>
                        </el-tooltip>
                    <h6 class="post-title mb-15 text-limit-2-row font-medium mt-10" style="text-align:left;">
                      <a @click="$commons.toWindodBlog(item.id)" href="javascript:void(0)">
                        {{overflowHidForText(item.title,9)}}
                        </a>
                        </h6>
                        <div v-html="item.slogan" class="mb-10" style="text-align:left;width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                          </div>
                    <div class="entry-meta meta-1 float-left font-x-small text-uppercase">
                      <span class="post-on">{{$commons.dateStr(item.updatetime)}} 更新</span>
                      <span class="post-by has-dot">{{$commons.formatNumber(item.views)}}阅读</span>
                    </div>
                  </div>
                </div>
              </li>
            
            </ul>
                  <i v-if="isLinkSearch" class="el-icon-loading ml-140"></i><br>
                  <span v-if="linkRec.current == Math.ceil(linkRec.total/linkRec.size)">没有更多了</span>
                </div>

            <input style="float:left;width:250px; border-radius: 25px;" class="mt-10 pl-5" placeholder="在此处搜索或者粘贴链接" v-model="linkA" />
            <el-button :icon="isLinkString(linkA)?'el-icon-link':'el-icon-search'" class="mt-5 ml-5" size="small" circle @click="setLink()"></el-button>
          </div>
          </div>
        </div>
  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce'
  import Editor from "@tinymce/tinymce-vue"
  import 'tinymce/themes/mobile/theme'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/codesample'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/toc'
  import 'tinymce/plugins/directionality'
  import 'tinymce/plugins/textpattern'
  import 'tinymce/plugins/autolink'
  import 'tinymce/plugins/charmap'
  import 'tinymce/plugins/visualblocks'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/plugins/insertdatetime'
  import 'tinymce/plugins/pagebreak'
  import 'tinymce/plugins/autosave'
  import 'tinymce/plugins/quickbars'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/link'
  import '../../../static/tinymce/plugins/lineheight'
  import '../../../static/tinymce/plugins/wordcount'
  import '../../../static/tinymce/plugins/colorpicker'

  import '@npkg/tinymce-plugins'
  import bus from '../../utils/bus.js'
  import lock from './js/Lock.js'
import Lock from './js/Lock.js';
  let Base64 = require('js-base64').Base64
  export default {
    components: {
      Editor
    },
    props:['content'],
    watch:{
      editContent(n,o) {
        if (this.$commons.isEmptyString(n)) {
          this.editContent = '<p></p>'
        }
        const pram = {
          name: 'content',
          data: this.editContent
        }
        bus.$emit('update', pram);
      }
    },
    data() {
      return {
        isUse:false,
        lock:new Lock(),
        time:new Date().getTime(),
        editContent:'<p></p>',
        window:window,
        linkT:'',
        linkA:'',
        isLinkSearch:false,
        isLink:false,
        linkRec:{
          txt:'',
          rec:[],
          current:1,
          size:2,
          total:0
        },
        // content: "",
        blogUrl: 'http://127.0.0.1:8084/#/',
        downloadUrl: 'http://dev.kingyin.club:9000/cloud/',
        apiKey: "sxatthvwb1oumh9c4xabkfp6zgt6bm6n9j7o0uozvqk5wcix", //key值从官网注册申请来的
        editConfig: {
          selector: "#tinymce",
          height: 780, //富文本高度
          language_url: 'http://dev.kingyin.club:9000/cloud/tinymce/langs/zh_CN.js', //中文包
          language: 'zh_CN', //中文
          // skin_url: '../../../static/tinymce/skins/ui/oxide',
          // content_css: '../../../static/tinymce/skins/content/default/content.css',
          skin_url: 'http://dev.kingyin.club:9000/cloud/tinymce/skins/ui/oxide',
          content_css: 'http://dev.kingyin.club:9000/cloud/tinymce/skins/content/default/content.css',
          plugins: 'colorpicker codesample code importword wordcount letterspacing lineheight indent2em table imagetools layout kityformula-editor lists toc directionality textpattern import autolink charmap visualblocks fullscreen insertdatetime pagebreak autosave quickbars media link',
          // menubar: 'file edit view format table tools help',
          toolbar: 'codesample ky-dividingline ky-link link | importword wordcount forecolor backcolor letterspacing lineheight indent2em alignleft aligncenter alignright | table colorpicker numlist bullist toc ltr rtl | kityformula-editor charmap | layout visualblocks | insertdatetime pagebreak restoredraft media  | code fullscreen',
          external_plugins: {
            'kityformula-editor': '../../../static/tinymce/plugins/kityformula-editor/plugin.min.js'
          },
          quickbars_image_toolbar: 'alignleft aligncenter alignright',
          quickbars_insert_toolbar: 'false',
          quickbars_selection_toolbar: 'bold italic | ky-link quicklink alignleft aligncenter alignright h2 h3 blockquote',
          charmap_append: [
              [0x2615, 'morning coffee'],
              [0x2600, 'sun'],
              [0x2601, 'cloud'],
          ],
          textpattern_patterns:[
            {start: '*', end: '*', format: 'italic'},
            {start: '**', end: '**', format: 'bold'},
            {start: '#', format: 'h1'},
            {start: '##', format: 'h2'},
            {start: '###', format: 'h3'},
            {start: '####', format: 'h4'},
            {start: '#####', format: 'h5'},
            {start: '######', format: 'h6'},
            {start: '1. ', cmd: 'InsertOrderedList'},
            {start: '* ', cmd: 'InsertUnorderedList'},
            {start: '- ', cmd: 'InsertUnorderedList' }
          ],
          letterspacing: "0px 2px 4px 6px 24px",
          table_icons: { // 以下下为默认配置
            'align-right-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm6 4h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2zm-6-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>',
            'align-left-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm0 4h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2zm0-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>',
            'align-center-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm3 4h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 1 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2zm-3-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>'
          },
          layout_options: {
            style: {
              'text-align': 'justify',
              'text-indent': '2em',
              'line-height': 1.5
            },
            filterTags: ['table>*', 'tbody'], //'table，'tbody','td','tr' 将会忽略掉 同时 table>*，忽略table 标签 以及所有子标签
            clearStyle: ['text-indent'], //text-indent 将会被清除掉
            tagsStyle: {
              'table': {
                'line-height': 3,
                'text-align': 'center'
              },
              'table,tbody,tr,td': { //支持并集选择
                'line-height': 2
              },
              'tr>td,table>tbody': { //支持, 精准定位 通过 ' > '
                'line-height': 3,
                'text-align': 'center'
              }
            }
          },
          valid_elements: '*[*]',
          valid_children: '*[*]',
          extended_valid_elements: 'style,link[href|rel],script',
          custom_elements: 'style,link,~link,script',
          setup(editor) {
            editor.ui.registry.addMenuButton('ky-dividingline', {
              text: '分割线',
              icon: 'horizontal-rule',
              fetch: function (callback) {
                var items = [{
                    type: 'menuitem',
                    text: '点状',
                    onAction: function (_) {
                      var spotHr = '<hr class="wp-block-separator is-style-dots"></hr>'
                      editor.insertContent(spotHr);
                    }
                  },
                  {
                    type: 'menuitem',
                    text: '线条',
                    onAction: function (_) {
                      var lineHr = '<hr class="section-divider">'
                      editor.insertContent(lineHr);
                    }
                  },
                ];
                callback(items);
              }
            });
            // 注册一个工具栏按钮名称
            editor.ui.registry.addButton('ky-link', {
              text: 'BLOG',
              icon: 'link',
              onAction: function () {
                var select = editor.selection.getContent();
                document.querySelector('#ky-link').click()
              }
            });

          },
          content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
        }
      }
    },
    methods: {
      
      setSelectionLink(url,title) {
        tinymce.activeEditor.selection.setContent('<a target="_blank" rel="noopener" href="'+url+'">'+this.linkT+title+'</a>');
        this.$notify({
          title: '饮用成功',
          message: '在文章引用了一个链接',
          type: 'success',
          position: 'bottom-right'
        });
      },
      async setLink() {
        if (this.isLinkString(this.linkA)) {
          // 添加link
          this.setSelectionLink(this.linkA,'');
        } else {
          this.linkRec = {
        txt:this.linkA,
        rec:[],
        current:1,
        size:2,
        total:0,
      }
      this.isLinkSearch = true;
        const pram = {
          context: this.linkRec.txt,
          current: this.linkRec.current,
          size: this.linkRec.size
        }
        var res = await this.$api.search.search(pram);
        if (res.code == 20000) {
          this.linkRec.rec = this.linkRec.rec.concat(res.data);
          this.linkRec.total = Number(res.data[0].context);
          this.isLink = true;
        }
        this.isLinkSearch = false;
        }
      },
      isLinkString(str) {
        if (str.startsWith('http://') || str.startsWith('https://') || str.startsWith('ftp://'))
          return true;
        return false;
      },
      closeLink() {
        this.isLink = false;
        this.linkRec = {
        txt:'',
        rec:[],
        current:1,
        size:2,
        total:0,
      }
      this.linkT = '';
      },
      load() {
        if (this.linkRec.current >= Math.ceil(this.linkRec.total/this.linkRec.size)) {
          return;
        }
        this.linkRec.current = this.linkRec.current+1;
        this.getLinks();
      },
      async getLinks() {
        let t = tinymce.editors[0].selection.getContent();
        if (this.$commons.isEmptyString(t)) {
          return;
        }
        // if (this.linkT == '') {
          this.linkT = t;
        // }
        this.isLinkSearch = true;
        this.linkRec.txt = t;
        const pram = {
          context: this.linkRec.txt,
          current: this.linkRec.current,
          size: this.linkRec.size
        }
        var res = await this.$api.search.search(pram);
        if (res.code == 20000) {
          if (res.data.length != 0) {
            this.linkRec.rec = this.linkRec.rec.concat(res.data);
          this.linkRec.total = Number(res.data[0].context);
          }
          
          this.isLink = true;
        }
        this.isLinkSearch = false;
      },
      overflowHidForText(val, max = 42) {
        let textLength = val.length;
        let resultText = '';
        if (textLength > max) {
          resultText = val.slice(0, max) + '...'
        } else {
          resultText = val
        }
        return resultText
      },
      decode(val) {
        return Base64.decode(val)
      },
      insert(html) {
        tinymce.editors[0].insertContent(html)
      },
      getUrl() {
        // 监听事件
        bus.$on('write', res => {
          if (res.name == 'file') {
            this.addFile(res.data)
          }
        })
      },
      async addFile(file) {
        if (this.isUse)
          await this.lock.wait();
        this.isUse = true;
            var time = new Date().getTime();
            // this.time = new Date().getTime();
            // bug 为加入N次文件，解决办法，在单位时间内只能出现一次
            if (time - this.time < 1000) {
              this.time = time;
              return;
            }
        var url = window.g.downloadUrl + file.path;
        var html = '<a href="' + url + '" wodnload="' + file.cname + '.' + file.suffix +
          '" class="el-link el-link--default is-underline"><i class="el-icon-download">' + file.cname + '.' + file
          .suffix + '</a>'
        switch (file.type) {
          case 'PIC':
            html = '<img src="' + url + '" style="border-radius: 25px;"></img>'
            break;
          case 'VIDEO':
            html =
              '<video controls="controls" controlslist="nofullscreen" type="video/mp4" preload="auto" playsinline="true" x-webkit-airplay="allow" x5-video-orientation="portraint" x5-playsinline="true" src="' +
              url + '" style="border-radius: 25px;"></video>'
            break;
          case 'MUSIC':
            html = '<audio controls="controls" type="audio/mp4" src="' + url + '" style="border-radius: 25px;"></audio>'
            break;
          default:
            break;
        }
        this.insert(html);
        this.isUse = false;
        this.lock.notify();
        this.$notify({
          title: '添加成功',
          message: '在文章添加了一个' + file.type + '项目',
          type: 'success',
          position: 'bottom-right'
        });
      },
      showMain() {
        // 监听事件
        bus.$on('clear', res => {
          if (res.name == 'edit') {
            this.editContent = '<p></p>';
          }

        })
      },
    },
    mounted() {
      this.showMain();
      this.editContent = this.content;
      tinymce.init({});
      this.getUrl();
    },
    beforeDestroy() {
      bus.$off('write')
    }
  }

</script>
<style scoped>

</style>
